# -*- encoding:utf8 -*-
from django.utils import timezone
from datetime import datetime, date, time, timedelta
from attendance.models import AvaiLeave, LeaveApplication
from attendance.tool_func import get_or_new, get_or_none
from attendance.convert import i2t, t2i, date2str, str2dt,i2day,dt2str,us2ls,ts2dls,day2t,h2t
import re
from staff.models import StaffInfo
import json


def update_leave_application(dc):
    """
    dc: leave_detail的反向字典
     {
        'empid':leave.staff.employee_id,
        'name':leave.staff.cn_name,
        'status':leave.status,
        'id':leave.id,
        'span':leave_span(leave),
        'category':leave.category,
        'reason':leave.reason,
        'start_time':leave.start_time,
        'end_time':leave.end_time,
        'create_time': dt2str(timezone.localtime(leave.create_time)),
        'leaders':leaders
        }
    """
    app=get_or_none(LeaveApplication,id=dc.get('id'))
        
    if app:
        app.status=dc.get('status',app.status)
        app.category=dc.get('category',app.category)
        app.reason=dc.get('reason',app.reason)
        app.start_time=dc.get('start_time',app.start_time)
        app.end_time=dc.get('end_time',app.end_time)
        record= dc.get('check_record')
        if record:
            app.check_record=json.dumps(record)
        app.save()
        #pump_chain(app)
        return app
    return None



def update_availeave(row_dict):
    """用字典更新availeave
    span:{value:xxx,unit:xxx}
    unit是day或者hour
    """
    row_id=row_dict.get('id')
    avai=get_or_none(AvaiLeave,id=row_id)
    if avai:
        staff=get_or_none(StaffInfo,employee_id=row_dict.get('empid'))
        if staff:
            avai.staff=staff
        avai.category=row_dict.get('category',avai.category)
        span=row_dict.get('span')
        if span:
            unit=span.get('unit')    # 如果hour，则按照hour处理，
            if unit=='hour':
                avai.span=h2t(span['value'])
            elif unit=='day':
                avai.span=day2t(span['value'])
            else:
                raise UserWarning,'in funcion update_availeave , unit not set'
        #if row_dict.get('used'):         # used是系统管理的，不能由外部更改
            #avai.used=day2t(row_dict.get('used'))
        avai.start_date=row_dict.get('start_date',avai.start_date)
        avai.is_valid=row_dict.get('is_valid',avai.is_valid)
        avai.note=row_dict.get('note',avai.note)
    avai.save()
    return avai
    

def add_annual(staff,year,span):
    """
    用于Hr给用户添加年假
    """
    pass

def add_swapoff(staff,start_date,span):
    """
    用于Hr给用户添加调休
    """
    pass
 
    
# def reject_application(app):
    # """
    # """
    # app.usedleave.all().delete()
    # app.status = 'rejected'
    # app.save()    
    
# def revoke_application(app):
    # """
    # 撤销请假
    # @type app: LeaveApplication ,需要撤销的假期记录对象
    # """
    # app.usedleave.all().delete()
    # app.status = 'revoked'
    # app.save()    



